//
//  Util.m
//  TBRJL
//
//  Created by 程三 on 15/6/20.
//  Copyright (c) 2015年 程三. All rights reserved.
//

#import "Util.h"
#import "Reachability.h"

@implementation Util

/*
 NSUserDefaults可以存储的数据类型包括：NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary。如果要存储其他类型，则需要转换为前面的类型，才能用NSUserDefaults存储。
 */


+(void)setObject:(NSObject *)object key:(NSString *)key
{
    if(key == nil || object == nil)
    {
        return;
    }
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setValue:object forKey:key];
    //用synchronize方法把数据持久化到standardUserDefaults数据库
    [userDefault synchronize];
    
}


+(NSObject *)getValue:(NSString *)key
{
    NSObject *obj = nil;
    if(key != nil)
    {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        obj = [userDefault objectForKey:key];
    }
    
    return obj;
}


+(void)setBool:(BOOL)b key:(NSString *)key
{
    if(key == nil)
    {
        return;
    }
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setBool:b forKey:key];
    //用synchronize方法把数据持久化到standardUserDefaults数据库
    [userDefault synchronize];
    
}


+(BOOL)boolForkey:(NSString *)key{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults boolForKey:key];
}



+(BOOL)writeData:(NSData *)data path:(NSString *)path fileName:(NSString *)fileName
{
    BOOL b = false;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断目录是否存在
    if(![fileManager fileExistsAtPath:path])
    {
         //创建文件夹路径
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //判断文件是否存在
    NSString *fullPath = [path stringByAppendingPathComponent:fileName];
    if([fileManager fileExistsAtPath:fullPath])
    {
        //存在就先删除
        [fileManager removeItemAtPath:fullPath error:nil];
    }
    
    b = [fileManager createFileAtPath:fullPath contents:data attributes:nil];
    
    
    return b;
}

//根据数据读取路径
+(NSData *)getDataForPath:(NSString *)fullPath
{
    NSData *data = nil;
    if(fullPath == nil || fullPath.length == 0)
    {
        return data;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    data = [fileManager contentsAtPath:fullPath];
    
    return data;
}

//  解密
+(NSString *)getKey
{
    return @"G*GL%#C_";
}


//对象序列化成字符串
+ (NSString*)objectToJson:(NSObject *)object
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+(CGSize)getSizeWithString:(NSString *)content textSize:(float)size width:(float)width
{
    CGSize cgsize = CGSizeMake(0,0);
    if(content == nil || [@"" isEqualToString:content] || size <= 0)
    {
        return cgsize;
    }
    
//    [content boundingRectWithSize:<#(CGSize)#> options:<#(NSStringDrawingOptions)#> attributes:<#(NSDictionary *)#> context:<#(NSStringDrawingContext *)#>]

    cgsize = [content boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size]} context:nil].size;
    
    //cgsize = [content sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(width, 0)];
    //cgsize=[content sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size]}];
    return cgsize;
}


//#pragma mark 获取网络状态 0:没有网 1:WI-FI 2:手机移动网
+(int)getNetState
{
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable)
    {
        // 有wifi
        return 1;
    }
    else if ([conn currentReachabilityStatus] != NotReachable)
    {
        // 没有使用wifi, 使用手机自带网络进行上网
        return 2;
    }
    else
    {
        // 没有网络
        return 0;
    }
    
}
//获取当前前一天时间
+ (NSString *)getLastDayTime {
    
    NSDate * date = [NSDate date];//当前时间
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];//前一天
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:lastDay];
    return dateTime;
}



//获取当前时间
+ (NSString *)getCurrentTime {
    
    NSDate * date = [NSDate date];//当前时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}

+ (BOOL)isValidCarID:(NSString *)carID {
    if (carID.length!=7) {
        return NO;
    }
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-hj-zA-HJ-Z]{1}[a-hj-zA-HJ-Z_0-9]{4}[a-hj-zA-HJ-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    return [carTest evaluateWithObject:carID];
    
    return YES;
}

// 获取开始时间
+ (NSString *)getStartTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-01-01"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

//  获取查询多少天的时间
+ (NSString *)getStartTimeWithNumber:(int)days{
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *componets = [gregorian components:NSCalendarUnitWeekOfYear | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    NSDateFormatter *dateDay = [[NSDateFormatter alloc] init];
    [dateDay setDateFormat:@"yyyy-MM-dd"];
    [componets setDay:([componets day] - days)];
    NSDate *mydate = [gregorian dateFromComponents:componets];
    return [dateDay stringFromDate:mydate];
}



@end
